package ca.etsmtl.gti785.classes;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Observable;
import java.util.Observer;

import android.content.Context;

import ca.etsmtl.gti785.util.AppSavedSettings;
import ca.etsmtl.gti785.util.GPSTracker;
import ca.etsmtl.gti785.util.NotificationsPolling;
import ca.etsmtl.gti785.util.ServerSorter;

/**
 * This is a singleton used for the application. It contains and stocks almost every infos used by the application (list of servers, gps tracker, etc).
 * @author Étienne Faucher
 */
public class Application extends Observable implements Observer  
{
	private static Application _instance;
	private ArrayList<Server> _servers;
	private GPSTracker _tracker;
	private AppSavedSettings _settings;
	private boolean _loadingServers;
	private Fichier _selectedFichier;
	
	public static Application getInstanceOf()
	{
		if(_instance == null)
		{
			_instance = new Application();
		}
		
		return _instance;
	}
	
	private Application()
	{
		_servers = new ArrayList<Server>();
		_loadingServers = false;
	}
	
	public void LoadServers(Context context)
	{
		_settings = new AppSavedSettings(context);
		_loadingServers = true;
		_settings.Load();
		_loadingServers = false;
	}
	
	public ArrayList<Server> getServers()
	{
		Collections.sort(_servers, new ServerSorter());
		return _servers;
	}
	
	public Server getSelectedServer()
	{
		for(Server item:_servers)
		{
			if(item.IsSelected())
			{
				return item;
			}
		}
		
		return null;
	}
	
	public void SetTracker(GPSTracker tracker)
	{
		_tracker = tracker;
		_tracker.addObserver(this);
	}
	
	public GPSTracker getGPSTracker()
	{
		return _tracker;
	}
	
	public Fichier getSelectedFichier()
	{
		return _selectedFichier;
	}
	
	public void setSelectedFichier(Fichier fichier)
	{
		_selectedFichier = fichier;
	}
	
	public void AddServer(Server server)
	{
		boolean alreadyAdded = false;
		for(Server item: _servers)
		{
			if(item.getURL().equals(server.getURL()))
			{
				alreadyAdded = true;
				break;
			}
		}
		
		if(!alreadyAdded)
		{
		    server.addObserver(this);
			_servers.add(server);
			NotificationsPolling.getInstanceOf().AddServer(server);
		}
		
		if(!_loadingServers)
		{
			_settings.Save();
		}
	}
	
	public void RemoveServer(Server server)
	{
		NotificationsPolling.getInstanceOf().RemoveServer(server);
		_servers.remove(server);
		
		if(!_loadingServers)
		{
			_settings.Save();
		}
	}

	@Override
	public void update(Observable observable, Object data) 
	{
		setChanged();
		notifyObservers();
	}
}
